export default class Snake {
  constructor(map, food) {
    this.map = map;
    this.data = [{
        x: 3,
        y: 5,
        color: "green"
      },
      {
        x: 2,
        y: 5,
        color: "#fff"
      },
      {
        x: 1,
        y: 5,
        color: "#fff"
      },
      {
        x: 0,
        y: 5,
        color: "#fff"
      },
    ];
    this.direction = "right";
    this.map.setData(this.data);
  }
  move() {
    let i = this.data.length - 1;
    this.lastData = {
      x: this.data[i].x,
      y: this.data[i].y,
      color: this.data[i].color,
    };
    // 让后边每一格走到前一个位置
    for (let i = this.data.length - 1; i > 0; i--) {
      this.data[i].x = this.data[i - 1].x;
      this.data[i].y = this.data[i - 1].y;
    }
    // 根据方向移动
    switch (this.direction) {
      case "left":
        this.data[0].x--;
        break;
      case "right":
        this.data[0].x++;
        break;
      case "top":
        this.data[0].y--;
        break;
      case "bottom":
        this.data[0].y++;
        break;
    }
  }
  changeDir(dir) {
    // 如果蛇本身左右移动只能修改成上下移动 如果蛇本身上下移动只能修改成左右移动
    if (
      ((this.direction === "left" || this.direction === "right") &&
        (dir === "left" || dir === "right")) ||
      ((this.direction === "top" || this.direction === "bottom") &&
        (dir === "top" || dir === "bottom"))
    ) {
      return false;
    } else {
      this.direction = dir;
      return true;
    }
  }
  eatFood() {
    this.data.push(this.lastData);
  }
}